package com.mutouren.web.frame;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mutouren.common.entity.Result;
import com.mutouren.common.entity.ResultCode;
import com.mutouren.common.entity.ResultInfo;
import com.mutouren.common.session.SessionConfig;
import com.mutouren.common.session.SessionManager;
import com.mutouren.common.session.UserInfo;
import com.mutouren.common.utils.CookieUtils;
import com.mutouren.common.utils.StringUtils;
import com.mutouren.modules.org.client.OrgAuthentication;
import com.mutouren.modules.org.client.OrgManager;
import com.mutouren.modules.org.model.Function;
import com.mutouren.web.WebUtils;

//import com.mutouren.common.log.LogAlias;
//import com.mutouren.common.log.LogManager;
//import com.mutouren.common.log.Logger;

@Controller
@RequestMapping(value="/frame")
public class FrameAction {
	
//	private static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.name());
//	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());
	
	private OrgManager orgManager = OrgManager.getInstance();
	private OrgAuthentication orgAuthentication = OrgManager.getInstance().getAuthentication();
	
	@RequestMapping(value="/login.action")
	public String login(
			@RequestParam(value="userName", required=false) String userName,
			@RequestParam(value="password", required=false) String password,
			HttpServletRequest request, HttpServletResponse response) {

		UserInfo userInfo = SessionManager.getSession().get(request);
		if (userInfo != null) {
			return "redirect:/frame/main.action";
		}

		request.setAttribute("actionName", WebUtils.getActionName(request));
		if (!WebUtils.isPost(request)) {
			return "frame/login";
		}
		
		List<String> errors = new ArrayList<String>();
		if(!this.validate(request, null, errors)) {
			ResultInfo<UserInfo> result = orgAuthentication.login(userName, password);
			
			if (result.getCode() == ResultCode.SUCCESS.value) {
				onLoginSuccessEvent(request, response, result.getInfo());
			} else {
				errors.add(result.getMessage());
			}
		}
		
		if (errors.size() == 0) {			
			return "redirect:/frame/main.action";
		} else {
			request.setAttribute("errorMsg", WebUtils.getErrorMessage(errors));
			request.setAttribute("userName", request.getParameter("userName"));
			request.setAttribute("password", request.getParameter("password"));			
			return "frame/login";
		}		
	}
	
	private void onLoginSuccessEvent(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo) {
		String sessionId = SessionManager.createSessionId();
		//ServletContext context = ContextLoader.getCurrentWebApplicationContext().getServletContext();
		userInfo.setLoginTime(new Date().getTime());
				
		// cookie
		CookieUtils.set(response, SessionConfig.cookieName, sessionId, request.getContextPath());
		// session
		SessionManager.getSession().set(request, sessionId, userInfo);
	}
	
	@RequestMapping(value="/main.action")
	public String main(HttpServletRequest request) {
		UserInfo userInfo = SessionManager.getSession().get(request);
		if (userInfo == null) {
			return "redirect:/frame/login.action";
		}
		
		request.setAttribute("userName", userInfo.getUserName());
		
		List<Function> listAllFunction = orgManager.getAllFunctionOfApp();
		int[] functionIds = orgManager.getFunctionIdsOfUser(userInfo.getUserId());		
		request.setAttribute("left_listFunction", OrgUtils.convertFunctionToJSON2(listAllFunction, convertToSet(functionIds), true));
		return "frame/main";
	}
	
	private Set<Integer> convertToSet(int[] source) {
		Set<Integer> result = new HashSet<Integer>();
		for(int e : source) {
			result.add(e);
		}		
		return result;
	}
	
	@RequestMapping(value="/modifyPassword.action")
	public String modifyPassword(
			String oldPassword, String newPassword, String repeatPassword,
			HttpServletRequest request, HttpServletResponse response) {
		
		request.setAttribute("actionName", WebUtils.getActionName(request));
		if (!WebUtils.isPost(request)) {
			return "frame/modifyPassword";
		}
		
		List<String> errors = new ArrayList<String>();
		if(this.validate(request, null, errors)) {
			return WebUtils.failDialog(response, WebUtils.getErrorMessage(errors));
		}
		
		UserInfo userInfo = SessionManager.getSession().get(request);
		Result result =this.orgAuthentication.modifyPassword(userInfo.getUserId(), oldPassword, newPassword);
		if (result.getCode() == ResultCode.SUCCESS.value) {
			return WebUtils.successDialog(response);
		} else {
			return WebUtils.failDialog(response, result.getMessage());
		}
		
	}	
	
	@RequestMapping(value="/logout.action")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		
		// cookie
		CookieUtils.delete(request, response, SessionConfig.cookieName, request.getContextPath());		
		// session
		SessionManager.getSession().delete(request);
								
		return "frame/login";
	}

	@RequestMapping(value="/welcome.action")
	public String welcome() {		
		return "frame/welcome";
	}
	
	@RequestMapping(value="/about.action")
	public String about() {		
		return "frame/about";
	}	
	
	public boolean validate(HttpServletRequest request, Object model, List<String> errors ) {
		String actionName = (String) request.getAttribute("actionName");

		if (actionName.equals("login")) {	
			String userName = request.getParameter("userName");
			String password = request.getParameter("password");
			if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
				errors.add("登录名，密码不能为空");
			}			
		}
		
		if (actionName.equals("modifyPassword")) {
			String oldPassword = request.getParameter("oldPassword");
			String newPassword = request.getParameter("newPassword");
			String repeatPassword = request.getParameter("repeatPassword");
			if (StringUtils.isBlank(oldPassword)) {
				errors.add("原密码不能为空");
			}			
			if (StringUtils.isBlank(newPassword)) {
				errors.add("新密码不能为空");
			}
			if (StringUtils.isBlank(repeatPassword)) {
				errors.add("重复新密码不能为空");
			}
			if (!(StringUtils.isBlank(newPassword) || StringUtils.isBlank(repeatPassword))) {
				if (!newPassword.equals(repeatPassword)) {
					errors.add("新密码、重复新密码不一致");
				}
			}
		}			

		return errors.size() > 0;
	}	
}
